package com.wu.leetcode.leetcode43;

import java.util.Arrays;

/**
 * Leetcode43-字符串相乘
 *
 * @author lynn
 * @date 2020/11/1 - 9:28
 */
public class Solution {
    public static String multiply(String num1, String num2) {
        char[] chs1 = num1.toCharArray();
        char[] chs2 = num2.toCharArray();

        int n1 = chs1.length;
        int n2 = chs2.length;

        char[] res = new char[n1 + n2];

        Arrays.fill(res, '0');

        for (int i = n1 - 1; i >= 0; i--) {
            for (int j = n2 - 1; j >= 0; j--) {
                int val = (chs1[i] - '0') * (chs2[j] - '0');
                int temp = res[i + j + 1] - '0' + val;
                res[i + j + 1] = (char) (temp % 10 + '0');
                res[i + j] = (char) (res[i + j] - '0' + temp / 10 + '0');

            }
        }
        StringBuilder builder = new StringBuilder();
        boolean flag = false;
        for (int i = 0; i < res.length; i++) {
            if (res[i] == '0' && !flag) {
                continue;
            }
            builder.append(res[i]);
            flag = true;
        }
        return builder.length() == 0 ? "0" : builder.toString();
    }

    public static void main(String[] args) {
        String multiply = multiply("123", "456");
        System.out.println(multiply);
    }
}
